package com.zzrc.grape.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.jdbc.ScriptRunner;

import java.io.Reader;
import java.nio.charset.Charset;
import java.sql.Connection;
import java.sql.DriverManager;

public class ScriptRunnerExecSql {
    private static final String dbHost="192.168.15.31";               // 数据库地址
    private static final String dbName="peony";                       // 数据库名称
    private static final String userName = "qa";                      // 登录名称
    private static final String userPassword = "pAqk5wPY9L48QMxd";    // 登录密码
    private static final String dbPort="3306";                        // 数据库端口号

    public static void execSql() {
        try {
            Connection conn = getMySqlConnection();
            ScriptRunner runner = new ScriptRunner(conn);
            Resources.setCharset(Charset.forName("UTF-8")); //设置字符集,不然中文乱码插入错误
            runner.setLogWriter(null);//设置是否输出日志
            // 绝对路径读取
//          Reader read = new FileReader(new File("f:\\test.sql"));
            // 从class目录下直接读取
            Reader read = Resources.getResourceAsReader("mysql/deleteUser.sql");
            runner.runScript(read);
            runner.closeConnection();
            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     *
     * @return 数据库连接
     * @throws Exception
     */
    public static Connection getMySqlConnection() throws Exception {
        Class.forName("com.mysql.jdbc.Driver");
        String url="jdbc:mysql://"+dbHost+":"+dbPort+"/"+dbName+"?useUnicode=true&characterEncoding=utf-8&port="+dbPort+"&autoReconnect=true&useSSL=false";
        return DriverManager.getConnection(url,userName,userPassword);
    }
}